using System.Collections;
using System.Collections.Generic;
using Net.Common;
using PEMath;
using PEPhysx;
using UnityEngine;

/****************************************************
// 功能：
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/26 21:59:58
*****************************************************/

public class BattleController : BaseController<BattleController>
{
    private GameObject battleGame;
    private BattleManager battleManager;
    private AudioSource battleAudio;

    public bool isTickFight;

    private uint keyId = 0;
    public uint KeyId => ++keyId;

    public PlayerControlWindow playerWindow;
    public ResultWindow resultWindows;

    public float SkillDisMultipler = 0.03f;
    
    public override void InitController()
    {
        base.InitController();
        Debug.Log("BattleController Init");
    }

    /// <summary>
    /// 初始化战斗UI
    /// </summary>
    public void InitBattleUI()
    {
        ui.Open(WindowName.Hp);
        ui.Open(WindowName.PlayerControl);
        //ui.DestoryWindow(WindowName.LoadHero);
        
        battleGame = new GameObject()
        {
            name = "battle"
        };
        battleManager = battleGame.AddComponent<BattleManager>();
        battleAudio = battleGame.AddComponent<AudioSource>();
        var mapConfig = resource.GetMapConfigData(model.mapId);
        battleManager.init(model.battleHero, mapConfig);

        SendByKcp(RequestType.BATTLE_START, new BattleRequest()
        {
            type = (int) RequestType.BATTLE_START
        });
        
    }
    
    
    /// <summary>
    /// 战斗结束
    /// </summary>
    /// <param name="isSuccess"></param>
    public void BattleEnd(bool isSuccess)
    {
        playerWindow.ShowResult(isSuccess);
    }


    #region 核心数据回调
    
    /// <summary>
    /// 开始战斗
    /// </summary>
    public void OnBattleStart(MsgInfo msgInfo)
    {
        battleManager.InitFollowTrans(model.currentIndex);
        playerWindow.InitSkillInfo();
        audioManager.PlayBGMusic(Constants.BG_GO_TIME);
        isTickFight = true;
        audioManager.PlayEntityAudio("welcombattle", battleAudio);
    }
    
    /// <summary>
    /// 接收玩家操作数据 移动、发送技能
    /// </summary>
    /// <param name="msgInfo"></param>
    public void OnNtfOpKey(MsgInfo msgInfo)
    {
        if (!isTickFight) return;
        
        NtfOpKey ntfOpKey = JsonUtility.FromJson<NtfOpKey>(msgInfo.data);
        battleManager.InputKey(ntfOpKey.keyList);
        battleManager.Tick();
    }
    
    /// <summary>
    /// 简易版聊天
    /// </summary>
    /// <param name="msgInfo"></param>
    public void OnChat(MsgInfo msgInfo) {
        playerWindow.AddChatMsg(msgInfo.data);
    }


    /// <summary>
    /// 结束战斗
    /// </summary>
    /// <param name="msgInfo"></param>
    public void OnBattleEnd(MsgInfo msgInfo)
    {
        if (battleManager != null) { battleManager.UnInit(); }
        Object.DestroyImmediate(battleGame);
        ui.GC();
        LobbyController.Instance.EnterLobby();
    }

    #endregion

    public IEnumerator ShowResult(bool isSuccess)
    {
        yield return new WaitForSeconds(0.5f);
        ui.Open(WindowName.Result);
        ui.DestoryWindow(WindowName.Hp);
        ui.DestoryWindow(WindowName.PlayerControl);
        resultWindows.SetBattleResult(isSuccess);
    }

    /// <summary>
    /// 获取所有环境碰撞体
    /// </summary>
    /// <returns></returns>
    public List<PEColliderBase> GetEnvColliders()
    {
        return battleManager.GetEnvColliders();
    }

    public void SetKillData(TeamEnum killHeroTeam)
    {
        playerWindow.SetKillData(killHeroTeam);
    }

    public void SetReviveTime(bool isRevive, int reviveSec = 0)
    {
        playerWindow.SetReviveTime(isRevive, reviveSec);
    }

    public MainLogicUnit GetSelfHero()
    {
        return battleManager.GetSelfHero(model.currentIndex);
    }

    /// <summary>
    /// 当前玩家所属队伍
    /// </summary>
    /// <returns></returns>
    public TeamEnum GetCurrentUserTeam()
    {
        var num = model.battleHero.Count / 2;
        return model.currentIndex < num ? TeamEnum.Blue : TeamEnum.Red;
    }

    /// <summary>
    /// 技能CD倒计时
    /// </summary>
    /// <param name="skillId"></param>
    /// <param name="cdTime"></param>
    public void EnterCdState(int skillId, int cdTime)
    {
        playerWindow.EnterCdState(skillId, cdTime);
    }

    public bool CheckUIInput() {
        return playerWindow.IsUIInput();
    }
    
    public void AddBullet(Bullet bullet) {
        battleManager.AddBullet(bullet);
    }
    
    public bool IsForbidSelfPlayerReleaseSkill() {
        return battleManager.IsForbidReleaseSkill(model.currentIndex);
    }
    
    public void PlayBattleFieldAudio(string name) {
        audioManager.PlayEntityAudio(name, battleAudio);
    }
    
    public void RefreshIncome(int income) {
        playerWindow.RefreshIncome(income);
    }
    
    
    #region API Function
    

    /// <summary>
    /// 发送移动帧到服务器
    /// </summary>
    /// <param name="logicDir"></param>
    /// <returns></returns>
    public bool SendMoveKey(PEVector3 logicDir)
    {
        
        if (CancelMove())
        {
            SendByKcp(RequestType.SEND_OP_KEY, new SendOpKeyRequest()
            {
                roomId = model.roomId,
                opKey = new OpKey()
                {
                    opIndex = model.currentIndex,
                    keyType = KeyType.Move,
                    moveKey = new MoveKey()
                    {
                        x = logicDir.x.ScaledValue,
                        z = logicDir.z.ScaledValue,
                        keyId = KeyId
                    }
                }
            });
        }
        else
        {
            return false;
        }
        
        
        return true;
    }

    public void SendSkillKey(int skillId) {
        SendSkillKey(skillId, Vector3.zero);
    }
    
    /// <summary>
    /// 发送技能施放指令
    /// </summary>
    /// <param name="skillId"></param>
    /// <param name="vector"></param>
    public void SendSkillKey(int skillId, Vector3 vector)
    {
        
        if (CancelReleaseSkill(skillId))
        {
            SendByKcp(RequestType.SEND_OP_KEY, new SendOpKeyRequest()
            {
                roomId = model.roomId,
                opKey = new OpKey()
                {
                    opIndex = model.currentIndex,
                    keyType = KeyType.Skill,
                    skillKey = new SkillKey()
                    {
                        skillId = (uint) skillId,
                        x_value = ((PEInt) vector.x).ScaledValue,
                        z_value = ((PEInt) vector.z).ScaledValue,
                    }
                }
            });
        }
        else
        {
            Debug.LogWarning("skill can not release");
        }

    }

    public bool CancelMove()
    {
        return battleManager.CancelMove(model.currentIndex);
    }
    
    public bool CancelReleaseSkill(int skillId)
    {
        return battleManager.CancelReleaseSkill(model.currentIndex, skillId);
    }

    #endregion
}
